<?php

Class User extends CI_Model {


	// Attributes
	var $id;
	var $username;
	var $group;
	function __construct()
	{
	parent::__construct();
	}

	


    function add_user($datauser) {




        // seleccionamos el ultimo id, para asignarte el auto_increment al siguiente
        $query = $this->db->query('SELECT max(id) from user');
        $row = $query->row_array();


        $id = $row['max(id)']; //el id se coge aqui, no en el post
        $id++;
        $datauser['password'] = hash('sha256', $datauser['password']);
        $date = substr($datauser['birth'], 6, 4) . '-' . substr($datauser['birth'], 3, 2) . '-' . substr($datauser['birth'], 0, 2);
        $datauser['birth'] = $date;
		$datauser['id'] = $id; //le a�adimos al vector $datauser el id

        $this->db->insert('user', $datauser);
    }

	
	function list_users() {
        $this->db->select('*');
		$this->db->from('user');
		$query = $this->db-> get();
        $rows = $query->num_rows();
        $query = $query->result_array();


        return 	$query;
	}

    function authenticate($username, $password) {
        $this->db->select('*');
        $this->db->from('user');
        $this->db->where('username', $username);
        $this->db->where('password', hash('sha256', $password));
        $this->db->where('status_user', 2);
        $this->db->limit(1);
        $query = $this->db->get();
        if ($query->num_rows() == 1) {
            $rows = $query->result();
            $this->id = $rows[0]->id;
            $this->username = $rows[0]->username;
            $this->group = $rows[0]->group;
            return $this;
        }
        return FALSE;
    }



	
	function count_users() {
        $query = $this->db->query("select COUNT(id) as qtd from user");
        $query = $query->result_array();

        return $query[0]['qtd'];
    }
	
	function delete_user($id){
		$this->db->delete('user', array('id' => $id)); 
	}
	
	function validate_user($id)
	{
		$this->db->select('status_user');
		$this->db->from('user');
		$this->db->where('id',$id);
		
		$query = $this->db-> get();
		$query= $query->result_array();
		
		$status= $query['0']['status_user'];
		
		
		if($status==0)
		{
			$status=2;
		}else
		{
			$status=0;
		}
		
		$data=array('status_user'=>$status);
		$this->db->where('id', $id);
        $this->db->update('user', $data); 
	}
	
	}


?>


